package com.insyte.activities;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.gson.Gson;
import com.insyte.R;
import com.insyte.adapters.ContactAdapter;
import com.insyte.adapters.ResultSearchAdapter;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.config.InsyteEnums;
import com.insyte.model.Contact;
import com.insyte.model.User;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.provider.ContactsContract.Contacts;
import android.widget.Toast;

public class ResultSearchActivity extends ActionBarActivity implements View.OnClickListener {
    private ListView lv_friend;
    private ResultSearchAdapter resultSearchAdapter;
    private List<User> users;
    private EditText edt_search;
    private RelativeLayout btn_filter;
    private InputMethodManager imm;
    private String url_community = "";
    private User user;
    private AQuery aQuery;
    private String type_find = "";

    // for contact
    private List<Contact> contacts;
    private List<String> contact_phones = new ArrayList<String>();
    private ContactAdapter contactAdapter;
    private SimpleCursorAdapter simpleCursorAdapter;
    private final static int[] TO_IDS = {
            android.R.id.text1
    };

    private static final String[] PROJECTION =
            {
                    Contacts._ID,
                    Contacts.LOOKUP_KEY,
                    Build.VERSION.SDK_INT
                            >= Build.VERSION_CODES.HONEYCOMB ?
                            Contacts.DISPLAY_NAME_PRIMARY :
                            Contacts.DISPLAY_NAME

            };
    private HashMap<String, String> list_contact;
    long mContactId;
    String mContactKey;
    Uri mContactUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_found_result);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        user = InsyteApp.getInstance().getUser();
        url_community = Constants.URL_API + "/friend/" + user.getId() + "/find?token=" + user.getToken() + "&name=";
        aQuery = new AQuery(this);
        Intent intent = getIntent();
        if (intent.hasExtra("find_type")) {
            type_find = intent.getStringExtra("find_type");
        }
        getView();
        setEvent();
        setAdapter();
        switch (type_find) {
            case "community":
                getAllFriend();
                break;
            case "contacts":
                getLisContact();
                break;
        }

    }

    private void getView() {
        lv_friend = (ListView) findViewById(R.id.lv_friend);
        edt_search = (EditText) findViewById(R.id.edt_search);
        btn_filter = (RelativeLayout) findViewById(R.id.btn_filter);
    }

    private void setEvent() {
        edt_search.setOnClickListener(this);
        btn_filter.setOnClickListener(this);

        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    actionFilterName();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edt_search:
                edt_search.setFocusableInTouchMode(true);
                edt_search.requestFocus(View.FOCUS_UP);
                imm.showSoftInput(edt_search, InputMethodManager.SHOW_IMPLICIT);
                break;
            case R.id.btn_filter:
                actionFilterName();
                break;
        }
    }

    private void setAdapter() {
        switch (type_find) {
            case "community":
                users = new ArrayList<User>();
                resultSearchAdapter = new ResultSearchAdapter(this, R.layout.row_friend_list, users);
                lv_friend.setAdapter(resultSearchAdapter);
                break;
            case "contacts":
                contacts = new ArrayList<Contact>();
                contactAdapter = new ContactAdapter(this, R.layout.item_contact, contacts);
                lv_friend.setAdapter(contactAdapter);
                break;
        }


    }

    private void getAllFriend() {
        //TODO: get list all find
        resultSearchAdapter.notifyDataSetChanged();
    }

    private void actionFilterName() {
        imm.hideSoftInputFromWindow(edt_search.getWindowToken(), 0);
        url_community += edt_search.getText().toString().trim();
        aQuery.ajax(url_community, String.class, new AjaxCallback<String>() {

            @Override
            public void callback(String url, String result, AjaxStatus status) {
                Log.e("result comminity", result);
            }
        });
    }

    private void getLisContact() {
        ContentResolver cr = getContentResolver();
        Uri uri_contact = Uri.parse("content://com.android.contacts/contacts");
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "account_type = ?", new String[]{"com.android.localphone"}, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                Contact new_contact = new Contact();
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id},
                            null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        contact_phones.add(phoneNo);
                    }
                    pCur.close();
                }
                new_contact.setId(id);
                new_contact.setName(name);
                contacts.add(new_contact);
            }
            contactAdapter.notifyDataSetChanged();
        }
    }
}
